package com.ooqiu.gaming.ui.search;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.Article;
import com.ooqiu.gaming.api.entities.ArticleListRes;
import com.ooqiu.gaming.base.BaseActivity;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.ui.article_detail.ArticleDetailActivity;
import com.ooqiu.gaming.ui.article_detail.VideoDetailActivity;
import com.ooqiu.gaming.ui.main.thread.index.content.IndexContentAdapter;
import com.ooqiu.gaming.view.DrawableItemDecoration;
import com.ooqiu.greendao.SearchRecordDao;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;


@Route(path = SearchActivity.PATH)
public class SearchActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, TextView.OnEditorActionListener, BaseQuickAdapter.RequestLoadMoreListener {
    public static final String PATH = "/gn/search";
    @BindView(R.id.tv_search)
    EditText mTvSearch;
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R.id.rv_search_rse)
    RecyclerView mRvSearchRse;

    IndexContentAdapter mIndexContentAdapter;

    List<Article> mArticles = new ArrayList<>();
    List<String> mWords = new ArrayList<>();
    List<SearchRecord> mSearchWords = new ArrayList<>();
    SearchRecordDao mSearchRecordDao;

    View mEmptyView;

    RecyclerView mRvThinkWork;
    RecyclerView mRvSearchWork;

    ThinkWordAdapter mThinkWordAdapter;

    GamingApi mGamingApi;

    private int page = 1;

    String keyWord = "";
    @Autowired()
    int search_type;


    LinearLayout mLaySearch;


    @Override
    public int initContentView() {
        return R.layout.activity_search;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        mGamingApi = getApplicationComponent().getGamingApi();
        mSearchRecordDao = getApplicationComponent().getDaoSession().getSearchRecordDao();
        mSearchWords.addAll(mSearchRecordDao.queryBuilder().limit(4).orderDesc(SearchRecordDao.Properties._id).list());
    }

    @Override
    public void initUiAndListener() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRvSearchRse.setLayoutManager(linearLayoutManager);
        mRvSearchRse.setAdapter(mIndexContentAdapter = new IndexContentAdapter(mArticles));
        mIndexContentAdapter.bindToRecyclerView(mRvSearchRse);
        mIndexContentAdapter.setEmptyView(R.layout.view_search_empty);
        mEmptyView = mIndexContentAdapter.getEmptyView();
        mRvThinkWork = mEmptyView.findViewById(R.id.rv_search_think);
        mLaySearch = mEmptyView.findViewById(R.id.lay_search_record);


        mEmptyView.findViewById(R.id.tv_clear_record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new QMUIDialog.MessageDialogBuilder(mContext)
                        .setTitle("清除搜索记录")
                        .setMessage("确定要清除吗？")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {

                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                mSearchRecordDao.deleteAll();
                                mSearchWords.clear();
                                mRvSearchWork.getAdapter().notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
        });
        mRvThinkWork.setAdapter(mThinkWordAdapter = new ThinkWordAdapter(mWords));

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        mRvSearchWork = mEmptyView.findViewById(R.id.rv_search_record);
        mRvSearchWork.setLayoutManager(gridLayoutManager);
        mRvSearchWork.setAdapter(new SearchWordAdapter(mSearchWords));
        ((SearchWordAdapter)mRvSearchWork.getAdapter()).setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                mArticles.clear();
                showLoading();
                keyWord = ((SearchRecord)adapter.getItem(position)).getWord();
                mTvSearch.setText(keyWord);
                mSearchRecordDao.insert(new SearchRecord(null, keyWord));
                search(keyWord);
                ((InputMethodManager) mContext.getSystemService(
                        Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                        SearchActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });


        mRvSearchWork.addItemDecoration(new DrawableItemDecoration(mRvSearchWork.getContext(), GridLayoutManager.HORIZONTAL));
        mRvSearchWork.addItemDecoration(new DrawableItemDecoration(mRvSearchWork.getContext(), GridLayoutManager.VERTICAL));

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(mContext);

        mRvThinkWork.setLayoutManager(linearLayoutManager1);
        mRvThinkWork.addItemDecoration(new DrawableItemDecoration(mRvThinkWork.getContext(), linearLayoutManager1.getOrientation()));
        mThinkWordAdapter.setOnItemClickListener(this);
        mRvSearchRse.addItemDecoration(new DrawableItemDecoration(mRvSearchRse.getContext(), linearLayoutManager.getOrientation()));
        mIndexContentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Article article = (Article) adapter.getItem(position);
                if (article.getContent_type() == 3) {
                    getRouter().build(VideoDetailActivity.PATH)
                            .withInt("news_id", article.getNews_id())
                            .navigation();
                } else {
                    getRouter().build(ArticleDetailActivity.PATH)
                            .withInt("news_id", article.getNews_id())
                            .navigation();
                }
            }
        });

        mIndexContentAdapter.setEnableLoadMore(true);
        mIndexContentAdapter.setOnLoadMoreListener(this, mRvSearchRse);
        mTvSearch.setOnEditorActionListener(this);
        mThinkWordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                mArticles.clear();
                showLoading();
                keyWord = adapter.getItem(position).toString();
                mTvSearch.setText(keyWord);
                mSearchRecordDao.insert(new SearchRecord(null, keyWord));
                search(keyWord);
                ((InputMethodManager) mContext.getSystemService(
                        Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                        SearchActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });

        mTvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    mArticles.clear();
                    mSearchWords.clear();
                    mSearchWords.addAll(mSearchRecordDao.queryBuilder().limit(4).orderDesc(SearchRecordDao.Properties._id).list());
                    mRvSearchWork.getAdapter().notifyDataSetChanged();
                    mLaySearch.setVisibility(View.VISIBLE);
                    mEmptyView.findViewById(R.id.tv_hint).setVisibility(View.GONE);
                    mIndexContentAdapter.notifyDataSetChanged();
                }
            }
        });

        fetchKeyWord();

    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return null;
    }

    @Override
    protected View statusLayoutId() {
        return null;
    }

    @OnClick(R.id.tv_cancel)
    public void onClick() {
        finish();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        mTvSearch.setText(adapter.getItem(position).toString());
    }


    private void search(String word) {



        mGamingApi.search(search_type,page, word)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<ArticleListRes>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(ArticleListRes articleListRes) {
                        if (articleListRes.getNext() == 0) {
                            mIndexContentAdapter.loadMoreEnd(page == 2);
                        } else {
                            mIndexContentAdapter.loadMoreComplete();
                        }

                        mArticles.addAll(articleListRes.getList());
                        if (page == 1) {
                            mIndexContentAdapter.setNewData(mArticles);
                        }
                        page++;


                        if (mArticles.isEmpty()) {
                            mEmptyView.findViewById(R.id.tv_hint).setVisibility(View.VISIBLE);
                            mLaySearch.setVisibility(View.GONE);
                        } else {
                            mLaySearch.setVisibility(View.VISIBLE);
                            mEmptyView.findViewById(R.id.tv_hint).setVisibility(View.GONE);
                        }

                        mIndexContentAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {
                        showContent();

                    }


                    @Override
                    public void handleError(Throwable e) {
                        if (page == 1) {
                            showRetry(e.getMessage());
                        } else {
                            mIndexContentAdapter.loadMoreFail();
                        }
                    }
                });
    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            page = 1;
            mArticles.clear();
            showLoading();
            keyWord = v.getText().toString();
            search(keyWord);
            mSearchRecordDao.insert(new SearchRecord(null, keyWord));
            ((InputMethodManager) v.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    SearchActivity.this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }

        return true;
    }

    @Override
    public void onLoadMoreRequested() {
        search(keyWord);
    }


    private void fetchKeyWord() {
        mGamingApi.searchKeyWord(search_type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<List<String>>() {
                    @Override
                    public void onNext(List<String> strings) {
                        mWords.addAll(strings);
                        mThinkWordAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
